import { defineStore } from 'pinia';
import { fishSpeciesApi } from '@/api';

export const useFishSpeciesStore = defineStore('fishSpecies', {
  state: () => ({
    fishSpecies: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchFishSpecies() {
      this.loading = true;
      try {
        const response = await fishSpeciesApi.getAll();
        this.fishSpecies = response.data || [];
        this.loading = false;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
      }
    },
    
    async addFishSpecies(fishData) {
      this.loading = true;
      try {
        const response = await fishSpeciesApi.add(fishData);
        // 添加成功后，将新数据添加到列表前面中
        this.fishSpecies.unshift(response.data);
        this.loading = false;
        return response.data;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    },
    
    async updateFishSpecies(id, fishData) {
      this.loading = true;
      try {
        const response = await fishSpeciesApi.update(id, fishData);
        // 更新成功后，更新本地数据
        const index = this.fishSpecies.findIndex(item => item.id === id);
        if (index !== -1) {
          this.fishSpecies[index] = { ...this.fishSpecies[index], ...response.data };
        }
        this.loading = false;
        return response.data;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    },
    
    async deleteFishSpecies(id) {
      this.loading = true;
      try {
        await fishSpeciesApi.delete(id);
        // 删除成功后，从列表中移除
        this.fishSpecies = this.fishSpecies.filter(item => item.id !== id);
        this.loading = false;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    }
  }
}); 